package com.baseDemo.web.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baseDemo.web.entity.DocInfoEntity;
import com.baseDemo.web.service.docinfo.DocInfoService;

@Controller
@RequestMapping(value = "/docinfo")
public class DocInfoController {
	@Resource
	DocInfoService docInfoService;

	@RequestMapping(value = "/upload")
	public @ResponseBody
	String upload(DocInfoEntity docInfoEntity, HttpServletRequest request) {
		return docInfoService.upload(docInfoEntity, request);
	}

	@RequestMapping(value = "/findDocInfoByCatalog")
	public @ResponseBody
	List<DocInfoEntity> findDocInfoByCatalog(@RequestParam String catalogId) {
		return docInfoService.findDocInfoByCatalog(catalogId);
	}

	@RequestMapping(value = "/download/{id}")
	public void download(HttpServletRequest request,
			HttpServletResponse response, String contentType,
			@PathVariable String id) throws Exception {
		DocInfoEntity docInfoEntity = docInfoService.getById(id);
		if(docInfoEntity!=null){
			response.setContentType("text/html;charset=UTF-8");
			request.setCharacterEncoding("UTF-8");
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;

			String ctxPath = request.getSession().getServletContext()
					.getRealPath("/");

			String downLoadPath = ctxPath + File.separator + docInfoEntity.getUrl();

			long fileLength = new File(downLoadPath).length();

			response.setContentType(contentType);
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String(docInfoEntity.getName().getBytes("utf-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));

			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			bis.close();
			bos.close();
		}
	}

}
